package com.psy.counseling.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.entity.Permission;
import com.psy.counseling.entity.Role;
import com.psy.counseling.entity.RolePermission;
import com.psy.counseling.entity.UserRole;
import com.psy.counseling.mapper.PermissionMapper;
import com.psy.counseling.mapper.RoleMapper;
import com.psy.counseling.mapper.RolePermissionMapper;
import com.psy.counseling.mapper.UserRoleMapper;
import com.psy.counseling.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.psy.counseling.vo.DeleteVO;
import com.psy.counseling.vo.PageVO;
import com.psy.counseling.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 梁学儒
 * @since 2022-05-31
 */
@Service("PermissionService")
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    public List<String> getPermissionById() {
        int userId = StpUtil.getLoginIdAsInt();
        QueryWrapper<UserRole> userRoleQW = new QueryWrapper<>();
        userRoleQW.eq("id", userId);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQW);
        List<String> res = new ArrayList<>();
        for(UserRole userRole : userRoles){
            Long roleId  = userRole.getRolId();
            QueryWrapper<Role> RoleQW = new QueryWrapper<>();
            RoleQW.eq("id", roleId);
            Role role = roleMapper.selectOne(RoleQW);
            QueryWrapper<RolePermission> W = new QueryWrapper<>();
            W.eq("id", role.getId());
            List<RolePermission> list = rolePermissionMapper.selectList(W);
            List<Long> perIdList = list.stream().map(RolePermission::getPerId).collect(Collectors.toList());
            for (Long perId : perIdList) {
                QueryWrapper<Permission> wrapper = new QueryWrapper<>();
                wrapper.eq("id", perId);
                Permission permission = permissionMapper.selectOne(wrapper);
                res.add(permission.getPermissionName()+"url:"+permission.getUrl());
            }
        }
        return res;
    }

    /**
     * 添加权限
     * @param permission
     * @return ResultVo
     */
    @Transactional
    public ResultVo addPermission(Permission permission){
        if(ObjectUtils.isEmpty(permission)){
            return ResultVo.builder().code("400").msg("添加失败!").data("权限不能为空").build();
        }else {
            LambdaQueryWrapper<Permission> PQW = new LambdaQueryWrapper<>();
            PQW.eq(Permission::getPermissionName,permission.getPermissionName());
            int i = this.count(PQW);
            if (i>0){
                return ResultVo.builder().code("400").msg("添加失败!").data("权限名已经被使用").build();
            }
            if(permissionMapper.insert(permission)>=1){
                return ResultVo.builder().code("200").msg("添加成功!").data(permission).build();
            }
            else {
                return ResultVo.builder().code("500").msg("添加失败!").data("系统错误").build();
            }
        }
    }

    /**
     * 删除权限
     * @param deleteVO
     * @return ResultVo
     */
    @Transactional
    public ResultVo deletePermission(DeleteVO deleteVO){
        if(ObjectUtils.isNotEmpty(deleteVO.getId())){
            if(this.removeById(deleteVO.getId())){
                return ResultVo.builder().code("200").msg("删除成功!").data(null).build();
            }
        }else if(ObjectUtils.isNotEmpty(deleteVO.getIds())){
            if(this.removeByIds(deleteVO.getIds())){
                return ResultVo.builder().code("200").msg("删除成功!").data(null).build();
            }
        }else {
            return ResultVo.builder().code("400").msg("删除失败!").data("id不能为空").build();
        }
        return ResultVo.builder().code("500").msg("删除失败!").data("系统错误").build();
    }

    /**
     * 查询权限
     * @param permission
     * @param page
     * @return ResultVo
     */
    @Transactional
    public ResultVo listPermissions(Permission permission, PageVO page) {
        Page<Permission> firstVisitPage = new Page<>(page.getPageNum(),page.getPageSize());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(permission.getId()),Permission::getId,permission.getId())
                .eq(ObjectUtils.isNotEmpty(permission.getPermissionName()),Permission::getPermissionName,permission.getPermissionName());
        firstVisitPage = this.page(firstVisitPage,queryWrapper);
        return ResultVo.builder().code("200").msg("查询成功!").data(firstVisitPage).build();
    }

    /**
     * 修改权限
     * @param permission
     * @return ResultVo
     */
    @Transactional
    public ResultVo updatePermission(Permission permission){
        if(ObjectUtils.isNotEmpty(permission.getId())){
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("id",permission.getId());
            Permission permission1 = permissionMapper.selectById(permission.getId());
            LambdaQueryWrapper<Permission> PQW = new LambdaQueryWrapper<>();
            PQW.eq(Permission::getPermissionName,permission.getPermissionName());
            int i = this.count(PQW);
            if (i>0){
                return ResultVo.builder().code("400").msg("修改失败!").data("此权限名已经被占用").build();
            }
            if (ObjectUtils.isNotEmpty(permission.getPermissionName())){
                permission1.setPermissionName(permission.getPermissionName());
            }
            if (ObjectUtils.isNotEmpty(permission.getUrl())){
                permission1.setUrl(permission.getUrl());
            }
            permissionMapper.update(permission1,wrapper);
            return ResultVo.builder().code("200").msg("修改成功!").data(permission1).build();
        }else {
            return ResultVo.builder().code("400").msg("修改失败!").data("权限id不能为空").build();
        }
    }

}
